package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import com.yu.alimsg.MsgUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private final MsgUtils msgUtils;
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public Result senCode(String phone) {
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式不正确");
        }
        String code = String.valueOf(new Random().nextInt(9)+1)+RandomUtil.randomNumbers(5);
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY +phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        log.info("发送给手机号{}验证码{}",phone,code);
        msgUtils.sendMsg(phone,code);
        return Result.ok("验证码发送成功");
    }

    @Override
    public Result login(LoginFormDTO loginForm) {
        String loginFormPhone = loginForm.getPhone();
        String code = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + loginFormPhone);
        if(code==null||!Objects.equals(code,loginForm.getCode())){
            return Result.fail("手机号或验证码错误");
        }
        User user = lambdaQuery().eq(User::getPhone, loginForm.getPhone()).one();
        if(user==null){
            user = createUserWithPhone(loginFormPhone);
        }
//        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        //保存用户到redis
        String token = UUID.randomUUID().toString(true);
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);

        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(), CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token,userMap);
        stringRedisTemplate.expire(LOGIN_USER_KEY+token,LOGIN_USER_TTL,TimeUnit.MINUTES);
        return Result.ok(token);
    }

    private User createUserWithPhone(String loginFormPhone) {
        User user=User.builder().phone(loginFormPhone)
                .nickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomNumbers(10))
                .build();
        save(user);
        return user;
    }

    @Override
    public Result queryUserById(Long userId) {
        User user = getById(userId);
        if(user==null){
            return Result.fail("用户不存在");
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        return Result.ok(userDTO);
    }


}
